package com.sword.ms_bwk.network;

import com.sword.ms_bwk.Utils;
import com.sword.ms_bwk.block.tile.ContainerFurnitureBlockEntity;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.core.BlockPos;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.sounds.SoundSource;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.network.simple.SimpleChannel;

import java.util.function.Supplier;

public class NetworkOfFurnitureCloseSound {
    public static final String VERSION = "1.0";
    public static SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel(new ResourceLocation(Utils.MOD_ID, "close_sound"), () -> VERSION, version -> version.equals(VERSION), version -> version.equals(VERSION));

    public static void register() {
        CHANNEL.registerMessage(0, SendPack.class, SendPack::encode, SendPack::decode, SendPack::handler);
    }

    public static class SendPack {
        private final BlockPos pos;

        public SendPack(BlockPos pos) {
            this.pos = pos;
        }

        public static void encode(SendPack pack, FriendlyByteBuf buf) {
            buf.writeBlockPos(pack.pos);
        }

        public static SendPack decode(FriendlyByteBuf buf) {
            return new SendPack(buf.readBlockPos());
        }

        //客户端用
        public static void handler(SendPack pack, Supplier<NetworkEvent.Context> ctx) {
            BlockPos pos = pack.pos;
            NetworkEvent.Context context = ctx.get();
            context.enqueueWork(() -> {
                ClientLevel level = Minecraft.getInstance().level;
                level.playLocalSound((double)pos.getX() + 0.5D, (double)pos.getY() + 0.5D, (double)pos.getZ() + 0.5D, ((ContainerFurnitureBlockEntity) level.getBlockEntity(pos)).getBlock().getUtilPackage().soundPackage.CLOSE_SOUND.get(), SoundSource.BLOCKS,0.5F, 1.0F, false);
            });
            context.setPacketHandled(true);
        }
    }
}
